package com.shlh.saas.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 反射工具类
 */
public class ReflectionUtils {
    private static final Logger log = LoggerFactory.getLogger(ReflectionUtils.class);

    /**
     * 获取对象字段值
     *
     * @param obj       目标对象
     * @param fieldName 字段名
     * @return 字段值
     */
    public static Object getFieldValue(Object obj, String fieldName) {
        if (obj == null || !StringUtils.hasText(fieldName)) {
            return null;
        }

        try {
            // 检查是否是嵌套字段（包含点号）
            if (fieldName.contains(".")) {
                String[] fieldPath = fieldName.split("\\.");
                Object currentObj = obj;
                
                // 逐层获取嵌套对象
                for (int i = 0; i < fieldPath.length - 1; i++) {
                    currentObj = getFieldValue(currentObj, fieldPath[i]);
                    if (currentObj == null) {
                        return null;
                    }
                }
                
                // 获取最终字段的值
                return getFieldValue(currentObj, fieldPath[fieldPath.length - 1]);
            }
            
            // 首先尝试使用getter方法
            String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            try {
                Method getter = obj.getClass().getMethod(getterName);
                return getter.invoke(obj);
            } catch (NoSuchMethodException e) {
                log.debug("No getter method found for field: {}, trying direct field access", fieldName);
            }

            // 如果没有getter方法，尝试直接访问字段
            Field field = getField(obj.getClass(), fieldName);
            if (field != null) {
                field.setAccessible(true);
                return field.get(obj);
            }
            
            // 特殊处理：如果对象是Map类型，尝试从Map中获取值
            if (obj instanceof Map) {
                return ((Map<?, ?>) obj).get(fieldName);
            }
            
            return null;
        } catch (Exception e) {
            log.error("Failed to get field value: {} from object: {}", fieldName, obj.getClass().getName(), e);
            return null;
        }
    }
    
    /**
     * 获取类的字段，包括父类字段
     *
     * @param clazz     类
     * @param fieldName 字段名
     * @return 字段
     */
    private static Field getField(Class<?> clazz, String fieldName) {
        if (clazz == null) {
            return null;
        }
        
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            // 在父类中查找
            return getField(clazz.getSuperclass(), fieldName);
        }
    }
    
    /**
     * 将对象转换为Map
     *
     * @param obj 对象
     * @return Map
     */
    public static Map<String, Object> objectToMap(Object obj) {
        if (obj == null) {
            return new HashMap<>();
        }
        
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            
            map.put(fieldName, value);
        }
        
        return map;
    }
} 